package com.example.myapplication;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;
import java.util.Map;

public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.ViewHolder> {
    private List<Chat> chats;
    private OnChatClickListener listener;

    public interface OnChatClickListener {
        void onChatClick(Chat chat);
    }

    public ChatAdapter(List<Chat> chats, OnChatClickListener listener) {
        this.chats = chats;
        this.listener = listener;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.chat_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Chat chat = chats.get(position);
        holder.nameText.setText(chat.getName());
        holder.messageText.setText(chat.getLastMessage());
        holder.timeText.setText(chat.getTime());
        // 设置头像
        holder.avatarImage.setImageResource(chat.getAvatarResourceId());

        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onChatClick(chat);
            }
        });
    }

    @Override
    public int getItemCount() {
        return chats.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView nameText, messageText, timeText;
        ImageView avatarImage;

        ViewHolder(View view) {
            super(view);
            nameText = view.findViewById(R.id.chatName);
            messageText = view.findViewById(R.id.lastMessage);
            timeText = view.findViewById(R.id.messageTime);
            avatarImage = view.findViewById(R.id.chatAvatar);
        }
    }
}